package com.rpc.consumer.client;

import com.rpc.common.entity.request.RPCDTO;
import com.rpc.center.discover.client.manager.ServerAddressManager;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Map;

@Getter
@Setter
public class RPCConsumerClient {
    private ServerAddressManager addressManager = ServerAddressManager.getAddressManagerInstance();

    /**
     * 实际与服务提供方通信，并消费的地方
     *
     * @param rpcdto
     * @return
     */
    public Object doConsumer(RPCDTO rpcdto) {
        //先获取可用的服务方地址
        Map.Entry<String, Integer> hostEntry = addressManager.getAvailableServer();
        if (hostEntry == null) {
            throw new RuntimeException("无可用服务器");
        }
        String hostAddress = hostEntry.getKey();
        int port = hostEntry.getValue();
        Object result = null;
        try (Socket socket = new Socket(hostAddress, port)) {
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(rpcdto);
            outputStream.flush();

            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            result = inputStream.readObject();
        } catch (IOException e) {
            //System.out.println("未知的服务端主机地址");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }
}
